package org.mapdroid.login;

import java.io.IOException;
import java.util.List;

import org.mapdroid.MapDroid;
import org.mapdroid.R;
import org.mapdroid.data.DataLoader;
import org.mapdroid.data.adt.Client;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnKeyListener, OnClickListener{
	public static final String CLIENT_OBJECT = "CLIENT_OBJECT";
	
	private EditText username;
	private EditText password;
	private Button ok;
	private Button cancella;
	private Button registrati;
	private List<Client> users;
	Intent i;
	SettingsActivity st;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        st=new SettingsActivity(/*extras.getString("impo")*/);
        username = (EditText) this.findViewById(R.id.edit_nome);
        password = (EditText) this.findViewById(R.id.edit_cognome);
        ok = (Button) this.findViewById(R.id.ok_button);
        cancella = (Button) this.findViewById(R.id.cancel_button);
        registrati = (Button) this.findViewById(R.id.register_button);
        
        ok.setOnClickListener(this);
        cancella.setOnClickListener(this);
        registrati.setOnClickListener(this);
        ok.setEnabled(false);
        
        username.setOnKeyListener(this);
        password.setOnKeyListener(this);
        
        users = super.getIntent().getParcelableArrayListExtra(Client.LIST);
        if(users == null){ 
	        try {
	        	DataLoader dataLoader = new DataLoader(this);
				dataLoader.loadUsers(R.raw.users);
				users = dataLoader.getUsersList();
	        } catch (NotFoundException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, R.string.file_not_found_error, Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, R.string.read_file_error, Toast.LENGTH_SHORT).show();
			}
        }
    }   
	
	@Override
	public void onResume(){
		super.onResume();
	}
	
	@Override
    public void onPause(){
    	super.onPause();
    }

    @Override
    public void onDestroy(){
    	super.onDestroy();
    }
	
	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event){	
		switch (v.getId()){
			case R.id.edit_nome:
			case R.id.edit_cognome:
				ok.setEnabled(username.getText().length() > 0 && password.getText().length() > 0);
			break;
		}
		return false;
	}
       
	public void onClick(View v){
		switch(v.getId()){
    		case R.id.register_button:
    			Intent surf = new Intent(Intent.ACTION_VIEW);
    			surf.setData(Uri.parse("http://www.comune.catania.it"));
    			this.startActivity(surf);
    			break;
    		case R.id.cancel_button:
    			username.setText("");
    			password.setText("");
    			username.requestFocus();
    			username.selectAll();
    			break;
    		case R.id.ok_button:
    			Client tmp = checkUserValue(username.getText().toString(), password.getText().toString());
    			if(tmp!=null){
    				SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(MapDroid.MAPDROID_PREFERENCES, Activity.MODE_APPEND).edit();
    				editor.putString(SettingsActivity.USERNAME, username.getText().toString());
    				editor.commit();
    			
    				sendPositiveAlert(tmp);
    			}
    			else{
    				sendNegativeAlert();
    			}
    			
    			break;
    	}
    }
    		
    private Client checkUserValue(String username, String password) {
		// TODO Auto-generated method stub
    	int size = users.size();
    	for(int i=0; i<size; i++){
    		String tmpUsername = users.get(i).getUsername();
    		String tmpPassword = users.get(i).getPassword();
    		if(tmpUsername.contentEquals(username) && tmpPassword.contentEquals(password))
    			return users.get(i);
    	}
		return null;
	}

	private void sendPositiveAlert(final Client c) {     
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(R.string.login_dialog_title);
		dialog.setMessage(R.string.login_confirmed_notify);
		dialog.setNeutralButton(R.string.ok_button_text, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				Intent i = new Intent();
				i.putExtra(LoginActivity.CLIENT_OBJECT, c);
				setResult(Activity.RESULT_OK, i);
				finish();
				
			}
			
			
		});
		dialog.show();  		
	}	
	
	private void sendNegativeAlert() {     
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(R.string.login_dialog_title);
		dialog.setMessage(R.string.login_error);
		dialog.setNeutralButton(R.string.ok_button_text, null);
		dialog.show();  		
	}

	public static void logout(Context context) {
		// TODO Auto-generated method stub
		SharedPreferences.Editor pref = context.getSharedPreferences(MapDroid.MAPDROID_PREFERENCES, Activity.MODE_APPEND).edit();
		pref.remove(SettingsActivity.USERNAME);
		pref.commit();
	}	
}
